﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlickrNet;
using System.Drawing;
using System.Threading;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;

namespace FlickrPhoneSync
{
    class FlickrCon
    {
        private Flickr flickr;
        private FoundUser user;
        private string targetPath;
        private int maxImages;
        PhotoCollection photos;
        private FlickrPhoneSyncUI.SetStatus setStatus;
        private bool terminate = false;

        public FlickrCon(string APIKey, string secret)
        {
            flickr = new Flickr(APIKey,secret);           
        }

        public void PrepareWorker( string userEmail, FlickrPhoneSyncUI.SetStatus setStatus, string targetPath = "img", int maxImages = int.MaxValue)
        {
            this.targetPath = targetPath;
            this.maxImages = maxImages;
            user = flickr.PeopleFindByEmail(userEmail);
            photos = flickr.PeopleGetPublicPhotos(user.UserId);
            this.setStatus = setStatus;
        }

        public void DoWork( object sender, DoWorkEventArgs args )
        {
            System.Net.HttpWebRequest httpWebRequest;
            System.Net.WebResponse webResponse;
            System.IO.Stream webStream;
            Image imageStream;
            string filename;

            if (!Directory.Exists(targetPath))
                Directory.CreateDirectory(targetPath);

            // Delete files if there are to much
            int numFiles = Directory.GetFiles(targetPath,"*.jpg").Length;
            if (numFiles > maxImages)
            {
                for (int j = maxImages; j < photos.Count; ++j) 
                {
                    filename = CreateFilename(photos[j]);

                    if( File.Exists(CreateFilePath(filename)) )
                        File.Delete(CreateFilePath(filename));
                }
            }
            
            for (int i = 0; i < maxImages; ++i )
            {
                Photo p = photos[i];

                filename = CreateFilename(p);

                if (!File.Exists(CreateFilePath(filename)))
                {
                    bool success = false;
                    try
                    {
                        int j = 1;
                        while (!success)
                        {
                            if (terminate)
                            {
                                setStatus(FlickrPhoneSyncUI.STATE_TERMINATED);
                                return;
                            }
                            setStatus("Downloading: " + filename + " try " + j++);

                            Thread.Sleep(5000);
                            httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(p.LargeUrl);
                            httpWebRequest.AllowWriteStreamBuffering = true;
                            httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
                            httpWebRequest.Timeout = 30000; //30 seconds
                            webResponse = httpWebRequest.GetResponse();
                            webStream = webResponse.GetResponseStream();
                            imageStream = Image.FromStream(webStream);
                            webResponse.Close();
                            imageStream.Save(CreateFilePath(filename));
                            success = true;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }

            }
            setStatus(FlickrPhoneSyncUI.STATE_FINISHED);
        }

        private string CreateFilePath(string fn)
        {
            return targetPath + "/" + fn;
        }

        private string CreateFilename(Photo p)
        {
            //if (p.Title != null && p.Title != "")
            //    return p.Title + ".jpg";
            //else
                return p.MediumUrl.Substring(p.MediumUrl.LastIndexOf("/") + 1);
        }

        internal void Kill()
        {
            setStatus(FlickrPhoneSyncUI.STATE_TERMINATING);
            terminate = true;
        }
    }
}
